package com.ruoyi.system.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.system.config.WxConfig;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.mapper.dispatchList.DispatchListMapper;
import com.ruoyi.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.OffsetDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@RestController
@RequestMapping("/dispatchList")
public class DispatchListController extends BaseController {

    @Autowired
    private DispatchListMapper dispatchListMapper;


    /**
     *  分页获取收获列表
     * @param dispatchList
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public TableDataInfo getDispatchList( DispatchList dispatchList) {

        startPage();
        List<DispatchList> list = dispatchListMapper.selectList(dispatchList);
        return getDataTable(list);

    }

//    发货
    @RequestMapping(value = "/send", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult send(@RequestBody  DispatchList dispatchList) {
        Integer result = dispatchListMapper.updateById(dispatchList);
        logger.info("发货成功~,result:{}", result);
        return AjaxResult.success("发货成功~");
    }

    @Autowired
    private WxConfigMapper wxConfigMapper;

    @Autowired
    private PayConfigMapper payConfigMapper;

    @Autowired
    private ExpressCompanyMapper expressCompanyMapper;

    @RequestMapping(value = "/sendByWx", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult sendByWx(@RequestBody  DispatchList dispatchList) {
        WxConfig wxConfig =  wxConfigMapper.selectOne();
        String appId = wxConfig.getAppId();
        String secret = wxConfig.getSecret();
        PayConfig payConfig = payConfigMapper.selectPayConfigByPayWay(0);
        String mchId = payConfig.getMchId();

        String accessToken = getAccessToken(appId, secret);


        JSONArray objects;
        String getExpressUrl = "https://www.kuaidi.com/index-ajaxselectinfo-"+dispatchList.getRealOrderNum()+".html";
        String result = HttpUtil.get(getExpressUrl);
        logger.info("result:{}", result);
        try {
            objects = JSONObject.parseArray(result);
        }catch (Exception e){
            return AjaxResult.error("快递单号获取物流公司信息获取失败,请联系风离修Bug~");
        }
        String expressName = objects.getJSONObject(0).getString("name");
        //根据快递公司名称获取快递编码
        String code = expressCompanyMapper.selectByExpressName(expressName);
        if (code == null) {
            return AjaxResult.error("快递公司不存在,请联系风离修Bug~");
        }


        OffsetDateTime now = ZonedDateTime.now().toOffsetDateTime();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
        String orderTime = now.format(formatter);
        System.out.println(orderTime);

        LinkedHashMap<Object, Object> reqMap =  new LinkedHashMap<Object, Object>();
//        reqMap.put("order_key",
//                        MapUtil.builder()
//                                .put("order_number_type", 1)
//                                .put("mchid", mchId)
//                                .put("out_trade_no", dispatchList.getDispatchOrderId()).build());

        reqMap.put("order_key",
                MapUtil.builder()
                        .put("order_number_type", 2)
                        .put("transaction_id", dispatchList.getTransactionId())
                        .put("mchid", mchId).build());
//                        .put("out_trade_no", dispatchList.getDispatchOrderId()).build()

        reqMap.put("logistics_type", 1);
        reqMap.put("delivery_mode", 1);
        reqMap .put("shipping_list", Collections.singletonList(
                        MapUtil.builder()
                                .put("tracking_no", dispatchList.getRealOrderNum())
                                .put("express_company", code)
                                .put("item_desc", "潮玩明信片发货").build()
                ));
        reqMap .put("upload_time", orderTime);
        reqMap .put("payer", MapUtil.builder()
                        .put("openid", dispatchList.getOpenId()).build());
        String requestBody = JSONObject.toJSONString(reqMap);
        logger.info("requestBody:{}", requestBody);
        logger.info("accessToken:{}", accessToken);
        String resp = HttpUtil.post("https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token="+accessToken, requestBody);
        logger.info("resp:{}", resp);
        JSONObject json = JSONObject.parseObject(resp);
        if (json.getIntValue("errcode")!= 0) {
            return AjaxResult.error("发货失败,请联系风离修Bug~");
        }
        dispatchList.setOriginOrderJson(requestBody);
        dispatchList.setProcessStatus(1);
        dispatchListMapper.updateById(dispatchList);

        return AjaxResult.success("发货成功~");
    }

    public String getAccessToken(String appId, String secret) {
        String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId +
                "&secret=" + secret;
        String result = HttpUtil.get(tokenUrl);
        JSONObject json = JSONObject.parseObject(result);
        return  json.getString("access_token");
    }


    @Autowired
    private YfsOrderListMapper yfsOrderListMapper;

    @Autowired
    private WxOrderListMapper wxOrderListMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserActiveCardRecordMapper userActiveCardRecordMapper;

    @Autowired
    private IUserService userService;




    @RequestMapping(value = "/returnGoods", method = RequestMethod.POST)
    @ResponseBody
    @Transactional
    public AjaxResult returnGoods(@RequestBody Map<String, String> dispatchId) {
        Integer id = dispatchId.get("id") == null? 0 : Integer.parseInt(dispatchId.get("id"));
        DispatchList dispatchList = dispatchListMapper.selectById(id);
        if (dispatchList == null) {
            return AjaxResult.error("发货单不存在");

        }
        if (dispatchList.getDispatchOrderId() == null || dispatchList.getDispatchOrderId().equals("请耐心等待发货")
        ) {
            List<Su> suList = JSONObject.parseArray(dispatchList.getOriginOrderJson(), Su.class);
            String userId = dispatchId.get("userId");
            //删除发货单
            dispatchList.setProcessStatus(-1); //-1 是退货
            dispatchListMapper.updateById(dispatchList);
            //更新订单状态 即更新订单状态信息 ，但是不删除订单
            suList.forEach(su -> {
                if (su.getOrderType() == 0) { //一番赏订单
                    List<YfsOrderList> orderLists = yfsOrderListMapper.selectList(userId, su.getGoodsListId(), 4, 0);//保险柜不算在回收里面

                    if (orderLists.size() < su.getNum()) {
                        throw new RuntimeException("退货出现问题，请联系客服");
                    }
                    int count = 0;
                    for (YfsOrderList orderList : orderLists) {
                        if (count >= su.getNum()) {
                            break;
                        }
                        orderList.setStatus(1); //1 是退货后转背包
                        yfsOrderListMapper.updateById(orderList);
                        count++;
                    }


                }else if (su.getOrderType() == 1) { //无限订单
                    List<WxOrderList> orderLists = wxOrderListMapper.selectList(userId, su.getGoodsListId(), 4, 0);//保险柜不算在回收里面

                    if (orderLists.size() < su.getNum()) {
                        throw new RuntimeException("退货出现问题，请联系客服");

                    }
                    int count = 0;
                    for (WxOrderList orderList : orderLists) {
                        if (count >= su.getNum()) {
                            break;
                        }
                        orderList.setStatus(1); //1 是退货后转背包
                        wxOrderListMapper.updateById(orderList);
                        count++;
                    }
                }
                else if (su.getOrderType() == 2) { //组组乐订单
                    List<UserActiveCardRecord> list = userActiveCardRecordMapper.selectList(
                         userId, su.getGoodsListId(), 4, 0, su.getNum()
                    );
                    if (CollectionUtil.isEmpty(list)) {
                        throw new RuntimeException("退货出现问题，请联系客服");
                    }
                    int count = 0;
                    for (UserActiveCardRecord record : list) {
                        if (count >= su.getNum()) {
                            break;
                        }
                        record.setStatus(1); //1 是退货后转背包
                        userActiveCardRecordMapper.updateUserActiveCardRecordV1(record);
                        count++;
                    }

                }
                else {
                    throw new RuntimeException("订单类型错误");
                }
            });
            //如果发货数量不足5件 则需要扣用户运费 扣10块钱
            int sum = suList.stream().mapToInt(Su::getNum).sum();
            if (sum < 5) {
                User user = userMapper.selectUserById(userId);

                user.setMoney(user.getMoney().add(BigDecimal.valueOf(10)));

                userMapper.updateUser(user);
                //更新用户余额变动记录
                String msg = "退货返运费";
                //更新记录
                int change = userService.updateRecords(userId,user.getMoney(),10,0,msg);
                logger.info("记录更新情况：{}",change);

            }
            return AjaxResult.success("退货成功");
        }else {
            return AjaxResult.error("发货单已发货,请耐心等待");
        }

    }
}
